package com.controller;


import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.entity.Dep;
import com.service.DepServletImpl;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@RestController
@RequestMapping("/api")
public class DepController {

    @Autowired
    private DepServletImpl depServlet;

    @Autowired
    private HttpServletRequest request;

    @Value("${upload.dir}")
    private String tmp;

//    @RequestMapping(value = "/searchDep",method = RequestMethod.GET)
    @RequestMapping({"/searchDep"})
    public ResponseBean searchDep(@RequestParam(defaultValue = "1")int page,@RequestParam(defaultValue = "10")int limit,Integer depId,String depName){
        IPage result=depServlet.searchDep(page,limit,depId,depName);
        return new ResponseBean(0,result.getTotal(),result.getRecords());
    }

    @RequestMapping(value = "/removeByIdDep")
    public ResponseBean removeByIdDep(String depId){
        boolean f=depServlet.removeById(depId);
        int code=f?200:500;
        return new ResponseBean(code,0,null);
    }

    @RequestMapping(value = "/addDep",method = RequestMethod.POST)
    public ResponseBean addDep(Dep dep){
        boolean f=depServlet.save(dep);
        int code=f?200:500;
        if (code==200){
            String descDir=request.getServletContext().getRealPath("/images");
            File descDirFile=new File(descDir);
            if (descDirFile.exists()==false){
                descDirFile.mkdirs();
            }

            FileUtil.copy(tmp+"/"+dep.getImage(),descDir+"/"+dep.getImage(),true);
        }

        return new ResponseBean(code,0,null);
    }

@RequestMapping(value = "/updateDep")
    public ResponseBean updateDep(Dep dep){
    System.out.println("dep:"+dep);
        boolean f=depServlet.updateById(dep);
        int code=f?200:500;
        if (code==200){
            String descDir=request.getServletContext().getRealPath("/images");
            File descFileDir=new File(descDir);
            if (descFileDir.exists()==false){
                descFileDir.mkdirs();
            }
            FileUtil.copy(tmp+"/"+dep.getImage(),descDir+"/"+dep.getImage(),true);
        }
        return new ResponseBean(code,0,null);
    }


}
